#include<iostream>
using namespace std;

#define e 50100
#define e1 21000
typedef struct Node
{
	int x,y;
	int w;
}node;

node edge1[e];

int sum,setnum;
int father[e1];
void exchange(int i,int j)
{
	int x1=edge1[i].x ,y1=edge1[i].y ,w1=edge1[i].w;
	edge1[i].x=edge1[j].x,  edge1[i].y=edge1[j].y,  edge1[i].w=edge1[j].w;
	edge1[j].x=x1,  edge1[j].y=y1,  edge1[j].w=w1;
}
int partion(int r,int l)
{
	int w1=edge1[l].w;
	int i=r-1,j=r; 
	for(;j<l;j++)
	{
		if(edge1[j].w>w1)
		{
			i++
			exchange(i,j);
		}

	}
	i++;
	exchange(i,l);
	return i;
}
void qsort(int r,int l)
{
	if(r>=l) return;
	int p=partion(r,l);
	qsort(r,p-1);
	qsort(p+1,l);
}

void makeset(int t)
{
	int i;
	for(i=0; i<t; i++)
	{
		father[i]=i;
	}
}

int findset(int i)
{
	if(i!=father[i])
	 father[i]=findset(father[i]);
	return father[i];
}
void unio(int x1,int y1)
{
	father[x1]=y1;
}
void kruskal(int t)
{
	int i,n,m;
	int x1,y1;
	for(i=0; i<t;i++)
	{
		x1=findset(edge1[i].x);
		y1=findset(edge1[i].y);
	
		if(x1!=y1)
		{
			unio(x1,y1);
			sum+=edge1[i].w;
		 
		}
	}
}
int main()
{ 
	int t1;
	scanf("%d", &t1);
	while(t1--)
	{ 
		memset(edge1,0,sizeof(edge1));
		memset(father,0,sizeof(father));
		int i,n,m;
		int x1,y1;
		int t;
		cin>>n>>m>>t;
		for(i=0; i<t; i++)
		{
			scanf("%d%d%d", &edge1[i].x,&edge1[i].y,edge1[i].w);
		 
			edge1[i].y+=n;
		}
		qsort(0,t-1);
		sum=0;
		 
		makeset(n+m);
	 
		kruskal(t);
		 
		printf("%d\n", 10000*(n+m)-sum);
	}
}

 